<template>
  <div id="header">
    <a-tooltip title="放大">
      <span class="iconfont header-iconfont" @click="handleZoom(0.2)">放大</span>
    </a-tooltip>
    <a-tooltip title="缩小">
      <span class="iconfont header-iconfont" @click="handleZoom(-0.2)">缩小</span>
    </a-tooltip>
    <a-tooltip title="撤销">
      <span class="iconfont header-iconfont" @click="graph.history.undo()">撤销</span>
    </a-tooltip>
    <a-tooltip title="删除选中">
      <span class="iconfont header-iconfont" @click="handleDelete">删除</span>
    </a-tooltip>
    <a-tooltip title="取消撤销">
      <span class="iconfont header-iconfont" @click="handleRedo()">取消撤销</span>
    </a-tooltip>
<!--    <a-tooltip title="全屏">-->
<!--      <span class="iconfont header-iconfont" @click="emit('full', true)">全屏</span>-->
<!--    </a-tooltip>-->
<!--    <a-tooltip title="退出全屏">-->
<!--      <span class="iconfont header-iconfont" @click="emit('full', false)">退出全屏</span>-->
<!--    </a-tooltip>-->
    <a-tooltip title="导出SVG">
      <span class="iconfont header-iconfont" @click="saveToSvgCustom">SVG</span>
    </a-tooltip>
    <a-tooltip title="导出JSON">
      <span class="iconfont header-iconfont" @click="saveToJson">JSON</span>
    </a-tooltip>
  </div>
</template>

<script setup>
import {defineProps, defineEmits, onMounted} from 'vue';
import { Graph, DataUri } from '@antv/x6';
import { Tooltip as ATooltip } from 'ant-design-vue';
import { unref } from 'vue';


onMounted(() => {
  // 假数据示例
  const dummyDevices = [
    { code: 'EQ-001', name: '焊接机器人', vendor: '张利民' },
    { code: 'EQ-002', name: '涂胶机', vendor: 'KUKA' },
    { code: 'EQ-003', name: '焊接机器人222', vendor: '张利民222' },
    { code: 'EQ-004', name: '涂胶机222', vendor: 'KUKA222' },
  ];
   const deviceList = dummyDevices;

});


const handleZoom = (val) => {
  if (props.graph && typeof props.graph.zoom === 'function') {
    props.graph.zoom(val);
  }
};
const handleRedo = () => {
  if (props.graph && props.graph.history && typeof props.graph.history.redo === 'function') {
    props.graph.history.redo();
  }
};
// --------------------------------删除节点
const handleDelete = () => {
  const graphInstance = props.graph;
  if (!graphInstance) {
    window.$message?.warning?.('图实例未初始化');
    return;
  }

  const selected = graphInstance.getSelectedCells?.() || [];
  console.log('Selected cells:', selected); // 调试
  if (!selected.length) {
    window.$message?.warning?.('请先选中要删除的节点或连线');
    return;
  }

  try {
    graphInstance.removeCells(selected);
    window.$message?.success?.('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    window.$message?.error?.('删除失败');
  }
};
// ------------------------------------

// 定义 props
const props = defineProps({
  graph: {
    type: Object,
    required: true,
  },
});


// 定义 emits
const emit = defineEmits(['full']);

const saveToSvgCustom = () => {
  const graph = unref(props.graph);
  if (!graph || !graph.view) {
    window.$message?.error?.('Graph 实例无效，无法导出 SVG');
    console.error('Graph instance:', graph);
    return;
  }

  const svgElement = graph.view.container.querySelector('svg');
  if (!svgElement) {
    window.$message?.error?.('未找到 SVG 元素');
    return;
  }

  // 获取画布实际尺寸
  const container = graph.view.container;
  const width = container.offsetWidth;
  const height = container.offsetHeight;

  // 克隆 SVG 元素
  const clonedSvg = svgElement.cloneNode(true);

  // 提取样式
  const styles = graph.view.container.querySelectorAll('style');
  let styleContent = '';
  styles.forEach((style) => {
    styleContent += style.outerHTML;
  });

  // 计算 viewBox（基于画布内容区域）
  const viewBox = `0 0 ${width} ${height}`;

  // 构造完整的 SVG 字符串
  const svgString = `
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" viewBox="${viewBox}">
      ${styleContent}
      ${clonedSvg.innerHTML}
    </svg>
  `;

  // 创建 Blob 并下载
  const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'chart.svg';
  a.click();
  window.URL.revokeObjectURL(url);
};

// 保存为 JSON

const saveToJson = () => {
  const graph = props.graph;
  // 从第一个节点提取 attribute 数据（假设所有节点共享相同属性）
  const firstNode = graph.getNodes()[0];
  const attributeData = firstNode ? {
    factoryName: firstNode.getData()?.factoryName || '',
    lineName: firstNode.getData()?.lineName || '',
    productName: firstNode.getData()?.productName || '',
    isLatest: firstNode.getData()?.isLatest || '',
    type: firstNode.getData()?.type || '',
    code: firstNode.getData()?.code || '',
    name: firstNode.getData()?.name || '',
    jph: firstNode.getData()?.jph || '',
    version: firstNode.getData()?.version || '',
  } : {};

  const graphData = {
    nodes: graph.getNodes().map((node) => {
      const data = node.getData() || {};
      // 仅保留 deviceList，移除其他属性
      return {
        id: node.id,
        shape: node.shape,
        x: node.position().x,
        y: node.position().y,
        width: node.size().width,
        height: node.size().height,
        attrs: node.getAttrs(),
        deviceList: data.deviceList || [],
      };
    }),
    edges: graph.getEdges().map((edge) => ({
      id: edge.id,
      source: edge.getSource(),
      target: edge.getTarget(),
      shape: edge.shape,
      attrs: edge.getAttrs(),
    })),
    attribute: attributeData,
  };
  const jsonData = JSON.stringify(graphData, null, 2);
  const blob = new Blob([jsonData], { type: 'application/json' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'graph.json';
  a.click();
  window.URL.revokeObjectURL(url);
};

</script>

<style scoped>
#header {
  display: flex;
  border-top: 1px solid #dfe3e8;
  padding-top: 5px;
  margin: 0;
  height: 35px;
  width: 100%;
}

.header-iconfont {
  margin-left: 20px;
  cursor: pointer;
  color: #595959;
}
</style>
